/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.resource.web;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.constants.LearnProgress;
import com.lczyfz.istep.common.constants.ResourceConstants;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.utils.JsonModel;
import com.lczyfz.istep.common.utils.StringUtils;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.modules.resource.entity.ResourceCourse;
import com.lczyfz.istep.modules.resource.entity.ResourceCourseware;
import com.lczyfz.istep.modules.resource.entity.ResourceCoursewareCourse;
import com.lczyfz.istep.modules.resource.entity.ResourceFile;
import com.lczyfz.istep.modules.resource.service.ResourceCourseService;
import com.lczyfz.istep.modules.resource.service.ResourceCoursewareCourseService;
import com.lczyfz.istep.modules.resource.service.ResourceCoursewareService;
import com.lczyfz.istep.modules.resource.service.ResourceFileService;
import com.lczyfz.istep.modules.sys.service.SystemService;
import com.lczyfz.istep.modules.sys.utils.UserUtils;
import com.lczyfz.istep.modules.teach.entity.TeachStudentCourseware;
import com.lczyfz.istep.modules.teach.service.TeachStudentService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 课程管理Controller
 * @author dh
 * @version 2017-01-16
 */
@Controller
@RequestMapping(value = "${adminPath}/resource/resourceCourse")
public class ResourceCourseController extends BaseController {

	@Autowired
	private ResourceCourseService resourceCourseService;
	@Autowired
	private ResourceCoursewareService resourceCoursewareService;
	@Autowired
	private ResourceCoursewareCourseService resourceCoursewareCourseService;
	@Autowired
	private ResourceFileService resourceFileService;
	@Autowired
	private TeachStudentService teachStudentService;
	@Autowired
	private SystemService systemService;
	@ModelAttribute
	public ResourceCourse get(@RequestParam(required=false) String id) {
		ResourceCourse entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = resourceCourseService.get(id);
		}
		if (entity == null){
			entity = new ResourceCourse();
		}
		return entity;
	}
	
	@RequiresPermissions("resource:resourceCourse:view")
	@RequestMapping(value = {"list", ""})
	public String list(ResourceCourse resourceCourse, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(systemService.isSuperAdmin()) {
			model.addAttribute("isSuperAdmin", "true");
		}
		else {
			model.addAttribute("isSuperAdmin", "false");
		}
		Page<ResourceCourse> page = resourceCourseService.findPage(new Page<ResourceCourse>(request, response), resourceCourse);
		model.addAttribute("page", page);
		return "modules/resource/resourceCourseList";
	}

	@RequiresPermissions("resource:resourceCourse:view")
	@RequestMapping(value = "form")
	public String form(ResourceCourse resourceCourse, Model model,String type) {
		logger.debug("resourceCourse=== [{}]",resourceCourse);
		ResourceCourseware resourceCourseware=new ResourceCourseware();
		List<ResourceCourseware> resourceCoursewareList=resourceCoursewareService.findList(resourceCourseware);
		int count=0;
		if(resourceCourse!=null&&resourceCourse.getId()!=null&&!resourceCourse.getId().equals(""))
		{
			logger.debug("课程id [{}]", resourceCourse.getId());
			ResourceCoursewareCourse resourceCoursewareCourse=new ResourceCoursewareCourse();
			resourceCoursewareCourse.setCourseId(resourceCourse.getId());
			List<ResourceCoursewareCourse> resourceCoursewareCourseList=resourceCoursewareCourseService.findList(resourceCoursewareCourse);


			for (int i = 0; i < resourceCoursewareList.size(); i++) {
				if(resourceCoursewareCourseList.size()==0)
				{
					break;
				}else {
					for (int j = 0; j < resourceCoursewareCourseList.size(); j++) {
						if (resourceCoursewareList.get(i).getId().equals(resourceCoursewareCourseList.get(j).getCoursewareId())) {
							resourceCoursewareList.get(i).setIsChoose("true");
							count++;
							resourceCoursewareCourseList.remove(j);
							break;
						}
//						if (j == resourceCoursewareCourseList.size() - 1) {
//							resourceCoursewareList.get(i).setIsChoose("false");
//						}
					}
				}

			}
		}
		if(systemService.isSuperAdmin())
		{
			model.addAttribute("isSuperAdmin", "true");
		}else
			model.addAttribute("isSuperAdmin", "false");
		if(type!=null&&type.equals("copy"))
		{

			resourceCourse.setCourseName(resourceCourse.getCourseName()+"-副本");
		}
		logger.debug("count: [{}]", count + "");
		logger.debug("课件数量 [{}]", resourceCoursewareList.size());
		model.addAttribute("resourceCoursewareList", resourceCoursewareList);
		model.addAttribute("type", type);
		model.addAttribute("resourceCourse", resourceCourse);
		return "modules/resource/resourceCourseForm";
	}

	/**
	 * 查看课程详情
	 * @param resourceCourse
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequiresPermissions("resource:resourceCourse:view")
	@RequestMapping(value = "detail")
	public String detail(ResourceCourse resourceCourse, Model model, HttpServletRequest request, HttpServletResponse response) {
		logger.debug("resourceCourse=== [{}]", resourceCourse);
		ResourceCourseware resourceCourseware=new ResourceCourseware();
		resourceCourseware.setCourseId(resourceCourse.getId());
		logger.debug("resourceCoursewareId=== [{}]", resourceCourseware.getCourseId());

		Page<ResourceCourseware> page = resourceCoursewareService.findPageByCourseId(new Page<ResourceCourseware>(request, response), resourceCourseware);
		logger.debug("page.getList().size()=== [{}]", page.getList().size());

		model.addAttribute("page", page);
		model.addAttribute("resourceCourse", resourceCourse);
		return "modules/resource/resourceCourseDetail";
	}
	@RequiresPermissions("resource:resourceCourse:edit")
	@RequestMapping(value = "save")
	public String save(ResourceCourse resourceCourse, Model model, RedirectAttributes redirectAttributes, String duallist,String type) {
		if (!beanValidator(model, resourceCourse)){
			return form(resourceCourse, model,type);
		}
		logger.debug("type: [{}]", type);

		if(type!=null&&type.equals("copy"))
		{
			logger.debug("复制课程！");
			ResourceCourse temp=resourceCourseService.findCourseByCourseName(resourceCourse);
			if (temp != null && temp.getCourseName().equals(resourceCourse.getCourseName())) {
				addMessage(redirectAttributes, "复制课程'" + resourceCourse.getCourseName() + "'失败，该课程已存在");
			}else {
				if (duallist == null || duallist.equals("")) {
					addMessage(redirectAttributes, "复制课程失败，请选择需要的课件");
				} else {
					ResourceCourse resourceCourse1=new ResourceCourse();
					resourceCourse1.setCourseName(resourceCourse.getCourseName());
					resourceCourse1.setCourseAttribute(resourceCourse.getCourseAttribute());
					resourceCourse1.setRemarks(resourceCourse.getRemarks());
					resourceCourse1.setClassHour(resourceCourse.getClassHour());
					resourceCourse1.setExperimentClassHour(resourceCourse.getExperimentClassHour());
					resourceCourseService.save(resourceCourse1);
					resourceCoursewareCourseService.save(duallist, resourceCourse1);
					addMessage(redirectAttributes, "复制课件'" + resourceCourse.getCourseName()+ "'成功");
				}
			}

		}else
		{
			if(resourceCourseService.get(resourceCourse)==null)
			{
				logger.debug("插入课程！");
				ResourceCourse temp=resourceCourseService.findCourseByCourseName(resourceCourse);
				if (temp != null && temp.getCourseName().equals(resourceCourse.getCourseName())) {
					addMessage(redirectAttributes, "添加课程'" + resourceCourse.getCourseName() + "'失败，该课程已存在");
				}else {
					if (duallist == null || duallist.equals("")) {
						addMessage(redirectAttributes, "添加课程失败，请选择需要的课件");
					} else {
//						resourceCourseService.save(resourceCourse);
						logger.debug("duallist [{}]", duallist);
						logger.debug("课程id [{}]", resourceCourse.getId());
						logger.debug("中间表服务 [{}]", resourceCoursewareCourseService);
						resourceCoursewareCourseService.save(duallist, resourceCourse);
						addMessage(redirectAttributes, "添加课程'" + resourceCourse.getCourseName() + "'成功");
					}

				}
			}else{
				ResourceCourse temp=resourceCourseService.findCourseByCourseName(resourceCourse);
				if(temp!=null&&!temp.getId().equals(resourceCourse.getId()))
				{
					addMessage(redirectAttributes,"修改课程失败，该课程已存在");
					return "redirect:"+Global.getAdminPath()+"/resource/resourceCourse/?repage";
				}

				if (duallist == null || duallist.equals("")) {
					addMessage(redirectAttributes, "修改课程失败，请选择需要的课件");
				} else {
					resourceCourseService.save(resourceCourse);
					resourceCoursewareCourseService.update(duallist, resourceCourse);
					addMessage(redirectAttributes, "修改课件'" + resourceCourse.getCourseName()+ "'成功");
				}

			}
		}
		return "redirect:"+Global.getAdminPath()+"/resource/resourceCourse/?repage";
	}
	
	@RequiresPermissions("resource:resourceCourse:edit")
	@RequestMapping(value = "delete")
	public String delete(ResourceCourse resourceCourse, RedirectAttributes redirectAttributes) {
		resourceCourseService.delete(resourceCourse);
		addMessage(redirectAttributes, "删除课程管理成功");
		return "redirect:"+Global.getAdminPath()+"/resource/resourceCourse/?repage";
	}

	//课程体系链接查看课程
	@RequestMapping(value = "viewCourseList")
	public String viewCourseList(HttpServletRequest request, HttpServletResponse response, ResourceCourse resourceCourse, Model model, String courseSystemId) {
		logger.debug("==Evan==viewCourseList1=="+courseSystemId);
		logger.debug("==Evan==viewCourseList2=="+resourceCourse.getCourseName());
//		logger.debug("==Evan==viewCourseList数据类型=="+courseSystemId.subSequence(0,1));
//		resourceCourse.setCourseSystemId((String) courseSystemId.subSequence(0, 1));
		resourceCourse.setCourseSystemId(courseSystemId);
		Page<ResourceCourse> page = resourceCourseService.viewCourseList(new Page<ResourceCourse>(request, response), resourceCourse);
		model.addAttribute("page", page);
		return "modules/teach/teachViewCourseList";
	}

	//根据课程属性获取课件
	@ResponseBody
	@RequestMapping(value = "findCoursewareListByAttribute")
	public JsonModel findCoursewareListByAttribute(@RequestParam(required = false) String attribute) {
		logger.debug("==dingh==" + attribute);

		JsonModel jsonModel = new JsonModel();
		ResourceCourseware resourceCourseware=new ResourceCourseware();
		resourceCourseware.setCoursewareAttribute(attribute);
		List<ResourceCourseware> resourceCoursewareList=resourceCoursewareService.findList(resourceCourseware);
		logger.debug("==dingh==" + resourceCoursewareList.size());
		jsonModel.setDataObj(resourceCoursewareList);
		return jsonModel;
	}

	/**
	 * 根据课程体系id查询课程列表展示
	 * @param resourceCourse
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("resource:resourceCourseware:view")
	@RequestMapping(value = "findPageByCoursesystemId")
	public String findPageByCoursesystemId(ResourceCourse resourceCourse, HttpServletRequest request, HttpServletResponse response, Model model) {
		logger.debug("courseId=== [{}]", resourceCourse.getCourseSystemId());
		Page<ResourceCourse> page = resourceCourseService.findPageByCoursesystemId(new Page<ResourceCourse>(request, response), resourceCourse);
		logger.debug("page.getList().size()=== [{}]", page.getList().size());
		model.addAttribute("page", page);
		return "modules/resource/resourceCourseList";
	}

	//	我的课程-课程列表展示
	@RequestMapping(value = "stuCourseList")
	public String stuCourseList(ResourceCourse resourceCourse, HttpServletRequest request, HttpServletResponse response, Model model) {
		//courseId是我的学习详情页里面的链接跳转
		String courseId = request.getParameter("courseId") ;
		logger.debug("==Evan==courseId=="+courseId);
		if(courseId != null && !courseId.equals("")){
			resourceCourse.setId(courseId);
		}
		resourceCourse.setUserId(UserUtils.getUser().getId());
		Page<ResourceCourse> page = resourceCourseService.stuCourseList(new Page<ResourceCourse>(request, response), resourceCourse);
		model.addAttribute("page", page);
		return "modules/teach/stuCourseList";
	}

	//我的课程-进入课程学习
	@RequestMapping(value = "enterCourseLearn")
	public String enterCourseLearn(String courseId, String classHour, Model model){
		//根据课程id获取所有课件
		List<ResourceCourseware> CoursewareList = resourceCoursewareService.findListByCourseId(courseId);
		//已完成课时
		int finishClassHour = 0;
        //课件路径
		String filePath = null;
		//默认加载第一个课件视频
		ResourceFile resourceFile = new ResourceFile();
		resourceFile.setResourceId(CoursewareList.get(0).getId());
		resourceFile.setType(ResourceConstants.videoMateria);
		List<ResourceFile> fileList = resourceFileService.findList(resourceFile);
		if(fileList.size() != 0){
			filePath = fileList.get(0).getUrl();
		}
		//初始化所有课件的课件进度
		for(ResourceCourseware aCoursewareList: CoursewareList){
			TeachStudentCourseware TeachStudentCoursewareList = teachStudentService.findTeachStudentCourseware(aCoursewareList.getId());
			if(TeachStudentCoursewareList == null){
				teachStudentService.LearnProgress(LearnProgress.unStart, aCoursewareList.getId());
			}
		}
		//获取所有课件的课件进度
		for(ResourceCourseware aCoursewareList: CoursewareList){
			//累计已完成课时
			if(teachStudentService.findTeachStudentCourseware(aCoursewareList.getId()).getLearnProgress() == LearnProgress.finish) {
				finishClassHour++;
			}
			aCoursewareList.setLearnProgress(teachStudentService.findTeachStudentCourseware(aCoursewareList.getId()).getLearnProgress() );
		}
		for(ResourceCourseware aCoursewareList: CoursewareList){
			logger.debug("==Evan==CoursewareList==" + aCoursewareList.getId() + "  , " + aCoursewareList.getLearnProgress());
		}
		model.addAttribute("CoursewareList", CoursewareList);
		model.addAttribute("resourceCourseware",CoursewareList.get(0));
		model.addAttribute("CoursewareId",CoursewareList.get(0).getId());
		model.addAttribute("CoursewareName",CoursewareList.get(0).getCoursewareName());

		model.addAttribute("courseId", courseId);
		model.addAttribute("classHour", classHour);
		model.addAttribute("finishClassHour", finishClassHour);
		model.addAttribute("filePath", filePath);
		return "modules/teach/stuCourseLearn";
	}

	//进入课程学习-判断第一个课件是否包含视频文件
	@ResponseBody
	@RequestMapping(value = "checkFirstHasVideoFile")
	public String checkFirstHasVideoFile(String courseId) {
		logger.debug("==Evan==checkFirstHasVideoFile=="+courseId);
		//根据课程id获取所有课件
		List<ResourceCourseware> CoursewareList = resourceCoursewareService.findListByCourseId(courseId);
		//根据课件id获取课件列表
		ResourceFile resourceFile = new ResourceFile();
		resourceFile.setResourceId(CoursewareList.get(0).getId());
		resourceFile.setType(ResourceConstants.videoMateria);
		List<ResourceFile> fileList = resourceFileService.findList(resourceFile);
		logger.debug("==Evan==fileList.size()=="+fileList.size());
		//课件路径
		String filePath = null;
		if(fileList.size() != 0){
			filePath = fileList.get(0).getUrl();
		}
		return filePath;
	}

	//我的课程-获取已学习课时
	@ResponseBody
	@RequestMapping(value = "getFinishClassHour")
	public String getFinishClassHour(String courseId){
		//根据课程id获取所有课件
		List<ResourceCourseware> CoursewareList = resourceCoursewareService.findListByCourseId(courseId);
		//已完成课时
		int finishClassHour = 0;
		for(ResourceCourseware aCoursewareList: CoursewareList){
			//累计已完成课时
			if(teachStudentService.findTeachStudentCourseware(aCoursewareList.getId()).getLearnProgress() == LearnProgress.finish) {
				finishClassHour++;
			}
		}
		return Integer.toString(finishClassHour);
	}

}